import {makeAutoObservable, reaction} from "mobx";
import {MeResponse} from "../apis/EmployeeApi";
import {Authority} from "../apis/RoleApi";
import dashboardPageStore from "../store/DashboardPageStore";
import {logOut} from "../apis/AuthorizationApi";
import {NumberIdAndName} from "../types/BasicModels";

let authorizationStorageKey = "Authorization";

export class EmployeeAuthorizationStore {

    authorization: string | null = null

    employee: MeResponse | null = null


    constructor() {
        makeAutoObservable(this)
        this.authorization = localStorage.getItem(authorizationStorageKey) ?? null
        reaction(() => this.authorization, (arg) => {
            if (arg) {
                localStorage.setItem(authorizationStorageKey, arg)
            } else {
                localStorage.removeItem(authorizationStorageKey)
            }
        })
    }

    get employeeAsNumberIdAndName():NumberIdAndName|null{
        return this.employee?{
            id: this.employee.id,
            name: this.employee.name
        }:null
    }

    setEmployee(employee: MeResponse) {
        this.employee = employee
    }

    setAuthorization(authorization: string | null) {
        this.authorization = authorization
    }

    async logOut() {
        this.authorization = null;
        this.employee = null;
        dashboardPageStore.clear()
    }

    get hasLogIn() {
        return !!this.authorization
    }

    hasAuthority(authority: Authority) {
        return !!this.employee?.authorities?.includes(authority)
    }

    hasAllAuthority(...authorities: Authority[]) {
        return authorities.every(authority => this.hasAuthority(authority))
    }

    hasAnyAuthority(...authorities: Authority[]) {
        return authorities.some(authority => this.hasAuthority(authority))
    }

}

export default new EmployeeAuthorizationStore()